package com.mathplayer.player.model.layoutschematas;

import gwt.g2d.client.graphics.Surface;

import java.util.Vector;

import com.mathplayer.player.geom.Area;
import com.mathplayer.player.geom.Font;
import com.mathplayer.player.geom.Size;
import com.mathplayer.player.interaction.InteractionSocket;
import com.mathplayer.player.model.LayoutSchemata;
import com.mathplayer.player.model.Token;

public class MFenced extends LayoutSchemata {

	protected Size openBracketSize;
	protected Size closeBracketSize;
	protected FenceType openFenceType;
	protected FenceType closeFenceType;
	
	public MFenced(Token content, FenceType openFenceType, FenceType closeFenceType){
		tokens = new Vector<Token>();
		tokens.add(content);
		this.openFenceType = openFenceType;
		this.closeFenceType = closeFenceType;
	}
	
	@Override
	public Size measure(InteractionSocket socket) {
		
		if (size != null)
			return size;
		
		Surface canvas = createCanvas();
		
		size = tokens.get(0).measure(socket);
		
		Font fenceFont = font.clone((int)size.height);
		canvas.setFont(fenceFont.toString());
		openBracketSize = new Size(canvas.measureText(FenceType.getOpenFence(openFenceType)), size.height);
		closeBracketSize = new Size(canvas.measureText(FenceType.getCloseFence(closeFenceType)), size.height);
		
		size.width +=  openBracketSize.width + closeBracketSize.width;
		
		removeCanvas(canvas);
		
		return size.clone();
	}

	@Override
	public void render(Surface canvas, Area area, InteractionSocket socket) {
		super.render(canvas, area, socket);
		
		canvas.setFont(font.clone((int)size.height).toString());
		canvas.fillText(FenceType.getOpenFence(openFenceType), exactArea.x, exactArea.y + getTextOffset((int)size.height));

		Area contentsArea = new Area(exactArea.x + openBracketSize.width, exactArea.y, tokens.get(0).measure(socket));
		tokens.get(0).render(canvas, contentsArea, socket);

		canvas.setFont(font.clone((int)size.height).toString());
		canvas.fillText(FenceType.getCloseFence(closeFenceType), exactArea.x + exactArea.width - closeBracketSize.width, exactArea.y + getTextOffset((int)size.height));
		
	}

	@Override
	public String toString() {
		return "(" + tokens.get(0).toString() + ")";
	}

	@Override
	public String toMathML() {
		return "<mfenced>" + tokens.get(0).toMathML() + "</mfenced>";
	}

}
